<!DOCTYPE HTML PUBLIC "-//ORA//DTD CD HTML 3.2//EN">
<HTML>
<HEAD>
<TITLE>[Chapter 5] 5.5 Anonymous Classes</TITLE>
<META NAME="author" CONTENT="David Flanagan">
<META NAME="date" CONTENT="Thu Jul 31 15:52:27 1997">
<META NAME="form" CONTENT="html">
<META NAME="metadata" CONTENT="dublincore.0.1">
<META NAME="objecttype" CONTENT="book part">
<META NAME="otheragent" CONTENT="gmat dbtohtml">
<META NAME="publisher" CONTENT="O'Reilly &amp; Associates, Inc.">
<META NAME="source" CONTENT="SGML">
<META NAME="subject" CONTENT="Java">
<META NAME="title" CONTENT="Java in a Nutshell">
<META HTTP-EQUIV="Content-Script-Type" CONTENT="text/javascript">
</HEAD>
<body vlink="#551a8b" alink="#ff0000" text="#000000" bgcolor="#FFFFFF" link="#0000ee">

<DIV CLASS=htmlnav>
<H1><a href='index.htm'><IMG SRC="gifs/smbanner.gif"
     ALT="Java in a Nutshell" border=0></a></H1>
<table width=515 border=0 cellpadding=0 cellspacing=0>
<tr>
<td width=172 align=left valign=top><A HREF="ch05_04.htm"><IMG SRC="gifs/txtpreva.gif" ALT="Previous" border=0></A></td>
<td width=171 align=center valign=top><B><FONT FACE="ARIEL,HELVETICA,HELV,SANSERIF" SIZE="-1">Chapter 5<br>Inner Classes and Other New Language Features</FONT></B></TD>
<td width=172 align=right valign=top><A HREF="ch05_06.htm"><IMG SRC="gifs/txtnexta.gif" ALT="Next" border=0></A></td>
</tr>
</table>

&nbsp;
<hr align=left width=515>
</DIV>
<DIV CLASS=sect1>
<h2 CLASS=sect1><A CLASS="TITLE" NAME="JNUT2-CH-5-SECT-5">5.5 Anonymous Classes</A></h2>

<P CLASS=para>
<A NAME="CH5.INNER.CLASSE5"></A><A NAME="CH5.CLASSES-ANON1"></A><A NAME="CH5.ANONYMOUS-CL1"></A>An anonymous class is essentially a local class
without a name.  Instead of defining a local class and then
instantiating it, you can often use an
anonymous class to combine these two steps.  
Anonymous classes are very
commonly used as adapter classes, like the one we saw in
<A HREF="ch05_04.htm#JNUT2-CH-5-EX-6">Example 5.6</A>.
As we'll see, anonymous classes (and their corresponding
anonymous objects) are created through another extension to
the syntax of the <tt CLASS=literal>new</tt> operator.  Thus, an anonymous
class is defined by a Java expression, not a Java
statement. This means that an anonymous class definition can
be included within a larger Java expression such as an
assignment or method call.

<P CLASS=para>
<A HREF="ch05_05.htm#JNUT2-CH-5-EX-8">Example 5.8</A>
shows the use of an anonymous class to implement the
<tt CLASS=literal>java.io.FilenameFilter</tt> interface.  The
implementation in this example is used to list only the
files whose names end with <I CLASS=emphasis>.java</I> from a specified
directory.

<DIV CLASS=example>
<h4 CLASS=example><A CLASS="TITLE" NAME="JNUT2-CH-5-EX-8">Example 5.8: Implementing an Interface with an Anonymous Class</A></h4>

<DIV CLASS=screen>
<P>
<PRE>
import java.io.*;
// A simple program to list all Java source code files in a directory
// specified as a command-line argument.
public class Lister 
{
  public static void main(String[] args)
  {
    File f = new File(args[0]);  // f represents the specified directory.
    // List the files in the directory, using the specified filter object.
    // The anonymous class is defined as part of a method call expression.
    String[] list = f.list(new FilenameFilter() {
      public boolean accept(File f, String s) { 
        return s.endsWith(".java"); 
      }
    });
    for(int i = 0; i &lt; list.length; i++)  // output the list
      System.out.println(list[i]);
  }
}
</PRE>
</DIV>

</DIV>

<P CLASS=para>
As you can see in
<A HREF="ch05_05.htm#JNUT2-CH-5-EX-8">Example 5.8</A>,
the syntax for defining an anonymous class and creating an
instance of that class is a regular <tt CLASS=literal>new</tt> expression,
followed by a class body definition in curly braces.  If the
name following the <tt CLASS=literal>new</tt> keyword is the name of a
class, the anonymous class is a subclass of the
named class.  If the name following <tt CLASS=literal>new</tt> specifies an
interface, as in our example, the anonymous class is 
an implementation of the interface.  In this case, the
anonymous class is always a subclass of <tt CLASS=literal>Object</tt>--there
is no way to specify an <tt CLASS=literal>extends</tt> clause (or an
<tt CLASS=literal>implements</tt> clause).  In addition, since this syntax
creates an anonymous class, there is obviously no way
to specify a name for the newly defined class.

<P CLASS=para>
Because an anonymous class has no name, it is not possible
to define constructors for it within the class body.  This
is one of the basic restrictions on anonymous classes.  Any
arguments you specify between the parentheses following the
superclass name in an anonymous class definition are
implicitly passed to the superclass constructor.  Anonymous
classes are commonly used to subclass simple classes that do
not take any constructor arguments, so the parentheses
in the anonymous class definition syntax are often
empty, as we saw in
<A HREF="ch05_05.htm#JNUT2-CH-5-EX-8">Example 5.8</A>.
When you use an anonymous class to implement an interface,
the constructor argument list is always empty, of
course, since the superclass constructor, <tt CLASS=literal>Object()</tt>,
expects no arguments.

<P CLASS=para>
One of the most elegant things about anonymous classes is
that they allow you to define a one-shot class exactly where
it is needed.  Other important features are the succinctness
of the syntax and the fact that no clutter is created by an
unnecessary name.

<P CLASS=para>
Since anonymous classes have no names, you may wonder
what the class files that represent them are named.  If you
compile the example shown in 
<A HREF="ch05_05.htm#JNUT2-CH-5-EX-8">Example 5.8</A>
you'll find that it produces two class files,
<I CLASS=emphasis>Lister.class</I> and <I CLASS=emphasis>Lister$1.class</I>.  Anonymous
classes are given numbers to produce unique class file
names based on the name of the containing class.

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="JNUT2-CH-5-SECT-5.1">Anonymous Class Indentation and Formatting</A></h3>

<P CLASS=para>
The common indentation and formatting conventions we are
familiar with for languages like Java and C begin to break
down somewhat once we start placing class definitions within
arbitrary expressions.  Based on their experience with inner
classes, the engineers at JavaSoft recommend the following
formatting rules, which are followed in
<A HREF="ch05_05.htm#JNUT2-CH-5-EX-8">Example 5.8</A>:

<P>
<UL CLASS=itemizedlist>
<li CLASS=listitem>The opening curly brace should not be on a line by itself;
instead, it should follow the close parenthesis of the
<tt CLASS=literal>new</tt> operator.  Similarly, the <tt CLASS=literal>new</tt> operator
should, when possible, appear on the same line as the assignment
or other expression of which it is a part.

<P>
<li CLASS=listitem>The body of the anonymous class should be indented relative
to the beginning of the line that contains the <tt CLASS=literal>new</tt>
keyword.

<P>
<li CLASS=listitem>The closing curly brace of an anonymous class should not be
on a line by itself either; it should be followed by
whatever tokens are required by the rest of the expression.
Often this is a semicolon or a close parenthesis
followed by a semicolon.  This extra punctuation serves as a
flag to the reader that this is not just an ordinary block of
code, and makes it easier to make sense of anonymous classes
in a code listing.

<P>
</UL>
</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="JNUT2-CH-5-SECT-5.2">Anonymous Classes versus Local Classes</A></h3>

<P CLASS=para>
As we've discussed, an anonymous class behaves just like a local
class, and is distinguished from a local class merely in the
syntax used to define and instantiate it.  In your own code,
when you have to choose between using an anonymous class or
using a local class, the decision often comes down to
stylistic matters.  You should use whichever syntax makes
your code clearer.  In general, you should consider using an
anonymous class instead of a local class if:

<P>
<UL CLASS=itemizedlist>
<li CLASS=listitem>The class has a very short body.

<P>
<li CLASS=listitem>Only one instance of the class is needed.

<P>
<li CLASS=listitem>The class is used right after it is defined.

<P>
<li CLASS=listitem>The name of the class does not make your code any easier to
understand.

<P>
</UL>
<P CLASS=para>
When considering the use of an anonymous class, there are
two important restrictions to bear in mind:

<P>
<UL CLASS=itemizedlist>
<li CLASS=listitem>An anonymous class has no name, and the syntax for defining
one combines definition with instantiation.  Thus, using an
anonymous class instead of a local class is not
appropriate if you need to create more than a single
instance of the class each time the containing block is
executed. 

<P>
<li CLASS=listitem>It is not possible to define constructors for anonymous
classes.  If your class requires a constructor, you must use
a local class instead.  However, as we'll see, the Java
syntax has been extended to allow "instance initializers" to
be defined for a class; an instance initializer can often
substitute for a constructor.

<P>
</UL>
<P CLASS=para>
Consider
<A HREF="ch05_05.htm#JNUT2-CH-5-EX-9">Example 5.9</A>,
which shows the <tt CLASS=literal>Enumeration</tt> class we've used
throughout this chapter implemented as an anonymous class
within the <tt CLASS=literal>enumerate()</tt> method of the
<tt CLASS=literal>LinkedList</tt> class. 
Compare it with
<A HREF="ch05_04.htm#JNUT2-CH-5-EX-5">Example 5.5</A>,
which shows the same class implemented as a local class.
In this case, because of the size of the class in question,
using local class syntax probably results in code that is a
little clearer.  Still, if you are a fan of anonymous
classes, you might choose to code the example in this way.

<DIV CLASS=example>
<h4 CLASS=example><A CLASS="TITLE" NAME="JNUT2-CH-5-EX-9">Example 5.9: An Enumeration Implemented with an Anonymous Class</A></h4>

<DIV CLASS=screen>
<P>
<PRE>
import java.util.*;
public class LinkedList 
{
  // Our nested top-level interface.  Body omitted here...
  public interface Linkable { ... } 
  // The head of the list.
  /* private */ Linkable head;  
  // Method bodies omitted here.
  public void addToHead(Linkable node) { ... }
  public Linkable removeHead() { ...  }
  // This method creates and returns an Enumeration object for this 
  // LinkedList.
  public Enumeration enumerate() 
  {
    // Instantiate and return this implementation.
    return new Enumeration() { 
      Linkable current = head; // This used to be in the constructor, but
                               // anonymous classes don't have constructors.
      public boolean hasMoreElements() {  return (current != null); }
      public Object nextElement() {
        if (current == null) throw new NoSuchElementException("LinkedList");
        Object value = current;
        current = current.getNext();
        return value;
      }
    };  // Note the required semicolon.  It terminates the return statement.
  }
}
</PRE>
</DIV>

</DIV>

<P CLASS=para>
As another example, consider
<A HREF="ch05_05.htm#JNUT2-CH-5-EX-10">Example 5.10</A>,
which shows the <tt CLASS=literal>createMenuItem()</tt> method of
<A HREF="ch05_04.htm#JNUT2-CH-5-EX-6">Example 5.6</A>
rewritten to use an anonymous class instead of a local
class.  In this case, using an anonymous class is probably
the right thing to do.

<DIV CLASS=example>
<h4 CLASS=example><A CLASS="TITLE" NAME="JNUT2-CH-5-EX-10">Example 5.10: Using an Anonymous Class as an Adapter</A></h4>

<DIV CLASS=screen>
<P>
<PRE>
MenuItem createMenuItem(String label, char shortcut, final int command)
{
  // First we create a MenuItem object.
  MenuItem item = new MenuItem(label, new MenuShortcut(shortcut));
  // Then we register an anonymous ActionListener for our new MenuItem.
  item.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) { app.doCommand(command); }
  });
  // And return the item, ready to be inserted into a menu.
  return item;
}
</PRE>
</DIV>

</DIV>

</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="JNUT2-CH-5-SECT-5.3">New Java Syntax for Anonymous Classes</A></h3>

<P CLASS=para>
We've already seen examples of the syntax for defining and
instantiating an anonymous class.  More formally, we can
write it as the following:

<P CLASS=para>
<DIV CLASS=screen>
<P>
<PRE>
<tt CLASS=literal>new class-name (</tt> [ <tt CLASS=literal>argument-list</tt> ] <tt CLASS=literal>) { class-body }</tt>
</PRE>
</DIV>

<P CLASS=para>
or

<P CLASS=para>
<DIV CLASS=screen>
<P>
<PRE>
<tt CLASS=literal>new interface-name () { class-body }</tt>
</PRE>
</DIV>

<P CLASS=para>
There is one additional
new piece of syntax to support anonymous classes.
As noted, anonymous classes cannot define constructors,
since they do not have names.  Therefore Java 1.1 adds a
feature known as an <I CLASS=emphasis>instance initializer</I>, which is similar
to the static initializer of Java 1.0.
<A HREF="ch05_05.htm#JNUT2-CH-5-EX-11">Example 5.11</A>
illustrates this new syntax.

<DIV CLASS=example>
<h4 CLASS=example><A CLASS="TITLE" NAME="JNUT2-CH-5-EX-11">Example 5.11: Java 1.1 Instance Initializers</A></h4>

<DIV CLASS=screen>
<P>
<PRE>
public class InitializerDemo 
{
  // This is an instance variable.
  public int[] array1;
  // This is an instance initializer.  It is an arbitrary block of code.
  // It runs for every new instance, after the superclass constructor 
  // and before the class constructor, if any.  It can serve the same
  // function as a constructor with no arguments.
  { 
    array1 = new int[10];
    for(int i = 0; i &lt; 10; i++) array1[i] = i; 
  }
  // The line below contains another instance initializer.  The instance
  // initializers for an object are run in the order in which they appear
  // in the class definition.
  int[] array2 = new int[10]; { for(int i=0; i&lt;10; i++) array2[i] = i*2; }
  static int[] static_array = new int[10];
  // By contrast, the block below is a static initializer.  Note the static
  // keyword.  It runs only once, when the class is first loaded.
  static { 
    for(int i = 0; i &lt; 10; i++) static_array[i] = i; 
  }
}
</PRE>
</DIV>

</DIV>

<P CLASS=para>
An instance initializer is simply a block of code inside
curly braces that is embedded in a class definition, where a
field or method definition normally appears.
[11]
A class (any class--not just anonymous classes) can have any
number of instance initializers.  The instance initializers
and any variable initializers that appear in field
definitions for the class are executed in the order they appear
in the Java source code.  These initializers are
automatically run after the superclass constructor has
returned but before the constructor, if any, of the current
class runs.

<blockquote class=footnote>
<P CLASS=para>[11] 
Notice that Java 1.1 now allows blocks of code to be
inserted in class definitions, and local class definitions
to be inserted in blocks of code.
</blockquote>
<P CLASS=para>
Because an instance initializer can serve the same function
as a no-argument constructor method, these initializers are
particularly useful for anonymous classes.  They can also be
useful in non-anonymous classes. Instance
initializers allow you to initialize an object's fields near
the definition of those fields, rather than deferring that
initialization to a constructor defined further away in the
class.  Used in this way, they can sometimes improve code
readability.

</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="JNUT2-CH-5-SECT-5.4">Restrictions on Anonymous Classes</A></h3>

<P CLASS=para>
Because anonymous classes are just a type of local class,
they share the same restrictions: an anonymous class cannot
define any <tt CLASS=literal>static</tt> fields, methods, or classes.
Since nested interfaces are implicitly <tt CLASS=literal>static</tt>, they
cannot be defined within anonymous classes.  Similarly,
interfaces cannot be defined anonymously.

<P CLASS=para>
Anonymous classes, like local classes, cannot be
<tt CLASS=literal>public</tt>, <tt CLASS=literal>private</tt>, <tt CLASS=literal>protected</tt>, or
<tt CLASS=literal>static</tt>.  In fact, the syntax for defining anonymous
classes does not allow any modifiers to be specified.

</DIV>

</DIV>


<DIV CLASS=htmlnav>

<P>
<HR align=left width=515>
<table width=515 border=0 cellpadding=0 cellspacing=0>
<tr>
<td width=172 align=left valign=top><A HREF="ch05_04.htm"><IMG SRC="gifs/txtpreva.gif" ALT="Previous" border=0></A></td>
<td width=171 align=center valign=top><a href="index.htm"><img src='gifs/txthome.gif' border=0 alt='Home'></a></td>
<td width=172 align=right valign=top><A HREF="ch05_06.htm"><IMG SRC="gifs/txtnexta.gif" ALT="Next" border=0></A></td>
</tr>
<tr>
<td width=172 align=left valign=top>Local Classes</td>
<td width=171 align=center valign=top><a href="index/idx_0.htm"><img src='gifs/index.gif' alt='Book Index' border=0></a></td>
<td width=172 align=right valign=top>Other New Features of Java 1.1</td>
</tr>
</table>
<hr align=left width=515>

<IMG SRC="gifs/smnavbar.gif" USEMAP="#map" BORDER=0> 
<MAP NAME="map"> 
<AREA SHAPE=RECT COORDS="0,0,108,15" HREF="../javanut/index.htm"
alt="Java in a Nutshell"> 
<AREA SHAPE=RECT COORDS="109,0,200,15" HREF="../langref/index.htm" 
alt="Java Language Reference"> 
<AREA SHAPE=RECT COORDS="203,0,290,15" HREF="../awt/index.htm" 
alt="Java AWT"> 
<AREA SHAPE=RECT COORDS="291,0,419,15" HREF="../fclass/index.htm" 
alt="Java Fundamental Classes"> 
<AREA SHAPE=RECT COORDS="421,0,514,15" HREF="../exp/index.htm" 
alt="Exploring Java"> 
</MAP>
</DIV>

</BODY>
</HTML>
